#!/usr/bin/env python
#
# A simple web service for English translation to LOLz
# Built with Kamaelia and PyLOLz
#
# Copyright (c)2008 Stephen Newey
# Licensed under the Mozilla Public License v1.1.
# http://www.mozilla.org/MPL/MPL-1.1.html
# 

import socket
import Axon
from Kamaelia.Chassis.ConnectedServer import SimpleServer
from Kamaelia.Protocol.HTTP.HTTPServer import HTTPServer
import Kamaelia.Protocol.HTTP.ErrorPages as ErrorPages
from lolz import Tranzlator

t = Tranzlator()

def requestHandlers(URLHandlers):
    def createRequestHandler(request):
        if request.get("bad"):
            return ErrorPages.websiteErrorPage(400, request.get("errormsg",""))
        else:
            for (prefix, handler) in URLHandlers:
                if request["raw-uri"][:len(prefix)] == prefix:
                    request["uri-prefix-trigger"] = prefix
                    request["uri-suffix"] = request["raw-uri"][len(prefix):]
                    return handler(request)
        return ErrorPages.websiteErrorPage(404, "No resource handlers could be found for the requested URL")
    return createRequestHandler
    
class WebTranzlator(Axon.Component.component):

    def __init__(self, request):
        super(WebTranzlator, self).__init__()
        self.request = request

    def main(self):
        resource = {
            'type'      : 'application/json',
            'statuscode': '200',
        }
        self.send(resource, "outbox"); yield 1
        page = {
            "data" : "{}",
        }
        self.send(page, "outbox"); yield 1
        self.send(Axon.Ipc.producerFinished(self), "signal")
        yield 1

def HTTPProtocol():
    return HTTPServer(requestHandlers([
        ['/', WebTranzlator],
    ]))

if __name__ == '__main__':
    SimpleServer(protocol=HTTPProtocol, port=8080, socketOptions=(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)).run()
